package com.bluelinelabs.conductor.demo.controllers;

import com.bluelinelabs.conductor.conductor.RouterTransaction;
import com.bluelinelabs.conductor.conductor.manager.ObjectManager;
import com.bluelinelabs.conductor.demo.ResourceTable;
import com.bluelinelabs.conductor.demo.controllers.base.BaseController;
import com.bluelinelabs.conductor.demo.util.RootItemMessage;
import ohos.aafwk.content.IntentParams;
import ohos.agp.animation.Animator;
import ohos.agp.animation.AnimatorGroup;
import ohos.agp.animation.AnimatorProperty;
import ohos.agp.colors.RgbColor;
import ohos.agp.components.*;
import ohos.agp.components.element.ShapeElement;
import ohos.app.Context;

import java.util.ArrayList;
import java.util.List;

/**
 * lipeiquan
 *
 * @since 2021-05-06
 */
public class CityGridController extends BaseController {
    RootItemMessage rootItemMessage;
    private Image image;
    private Image mImage;
    private boolean isFistStart = true;
    private boolean isDestroy = true;
    private Text tvTitle;
    private Text text;
    private ListContainer mListContainer;
    private ArrayList<CityModel[]> cityList = new ArrayList();
    private Component parse;

    public CityGridController() {
        super(ResourceTable.Layout_controller_city_grid);
    }

    public CityGridController(RootItemMessage rootItemMessage) {
        super(ResourceTable.Layout_controller_city_grid);
        this.rootItemMessage = rootItemMessage;
        ObjectManager.getInstance().addFinishAnimator(new ObjectManager.AnimatorChangeHandlerListener() {
            @Override
            public void cityGridControllerFinishAnimator(boolean isFistStart) {
                finishAnimator(isFistStart);
            }
        });
    }

    @Override
    public void onViewCreated(Component component) {
        title = "Shared Element Demos";
        ObjectManager.getInstance().setIdTitleAboutSetVisibility(Component.HIDE);
        if (isDestroy) {
            cityList.add(new CityModel[]{new CityModel(ResourceTable.Media_chicago, "Chicago"), new CityModel(ResourceTable.Media_jakarta, "Jakarta")});
            cityList.add(new CityModel[]{new CityModel(ResourceTable.Media_london, "London"), new CityModel(ResourceTable.Media_sao_paulo, "Sao Paulo")});
            cityList.add(new CityModel[]{new CityModel(ResourceTable.Media_tokyo, "Tokyo"), null});

            tvTitle = ((Text) component.findComponentById(ResourceTable.Id_title));
            mImage = ((Image) component.findComponentById(ResourceTable.Id_dot));
            mListContainer = ((ListContainer) component.findComponentById(ResourceTable.Id_list_container));


            tvTitle.setText(rootItemMessage.getText());
            ShapeElement shapeElement = new ShapeElement(component.getContext(), ResourceTable.Graphic_circle);
            shapeElement.setRgbColor(RgbColor.fromArgbInt(component.getContext().getColor(rootItemMessage.getImageColor())));
            mImage.setBackground(shapeElement);

            mListContainer.setItemProvider(new CityGridAdapter(cityList, getActivity().getContext()));

            DependentLayout cityRootLay = ((DependentLayout) component.findComponentById(ResourceTable.Id_city_grid_root));

            image = createImage(getActivity());
            text = createText(getActivity());
            cityRootLay.addComponent(image);
            cityRootLay.addComponent(text);

            component.getContext().getUITaskDispatcher().delayDispatch(new Runnable() {
                @Override
                public void run() {
                    startAnimator(isFistStart);
                }
            }, 50);
            isDestroy = false;
        }
    }

    private Image createImage(Context context) {
        ShapeElement shapeElement = new ShapeElement(context, ResourceTable.Graphic_circle);
        shapeElement.setRgbColor(RgbColor.fromArgbInt(context.getColor(rootItemMessage.getImageColor())));
        Image image = new Image(getActivity());
        image.setBackground(shapeElement);
        image.setHeight(rootItemMessage.getImageHeight());
        image.setWidth(rootItemMessage.getImageWidth());
        image.setTranslation(rootItemMessage.getImageLocation()[0] + 10, rootItemMessage.getImageLocation()[1] - 140);
        return image;
    }

    private Text createText(Context context) {
        Text text = new Text(getActivity());
        text.setText(rootItemMessage.getText());
        text.setTranslation(rootItemMessage.getTextLocation()[0] + 10, rootItemMessage.getTextLocation()[1] - 140);
        text.setTextSize(rootItemMessage.getTextSize());
        return text;
    }

    private void startAnimator(boolean isFistStart) {
        if (isFistStart) {
            AnimatorGroup animatorGroup = new AnimatorGroup();
            AnimatorProperty imageAm = image.createAnimatorProperty()
                    .moveFromX(rootItemMessage.getImageLocation()[0]).moveToX(mImage.getLocationOnScreen()[0])
                    .moveFromY(rootItemMessage.getImageLocation()[1] - 120).moveToY(mImage.getLocationOnScreen()[1] - 80)
                    .scaleX((float) mImage.getWidth() / (float) image.getWidth())
                    .scaleY((float) mImage.getHeight() / (float) image.getHeight());
            AnimatorProperty textAm = text.createAnimatorProperty()
                    .moveFromX(rootItemMessage.getTextLocation()[0]).moveToX(tvTitle.getLocationOnScreen()[0])
                    .moveFromY(rootItemMessage.getTextLocation()[1] - 120).moveToY(tvTitle.getLocationOnScreen()[1] - 80);
            animatorGroup.runParallel(imageAm, textAm);
            animatorGroup.setDelay(500);

            animatorGroup.setStateChangedListener(new Animator.StateChangedListener() {
                @Override
                public void onStart(Animator animator) {
                }

                @Override
                public void onStop(Animator animator) {
                }

                @Override
                public void onCancel(Animator animator) {
                }

                @Override
                public void onEnd(Animator animator) {
                    image.setVisibility(Component.INVISIBLE);
                    text.setVisibility(Component.INVISIBLE);
                    setComponentsVisibility(Component.VISIBLE);
                }

                @Override
                public void onPause(Animator animator) {
                }

                @Override
                public void onResume(Animator animator) {
                }
            });
            animatorGroup.start();
            this.isFistStart = false;
        }
    }


    private void finishAnimator(boolean isFistStart) {
        isDestroy = true;
        if (!isFistStart) {
            image.setVisibility(Component.VISIBLE);
            text.setVisibility(Component.VISIBLE);
            setComponentsVisibility(Component.INVISIBLE);

            AnimatorGroup animatorGroup = new AnimatorGroup();
            AnimatorProperty imageAm = image.createAnimatorProperty()
                    .moveFromX(mImage.getLocationOnScreen()[0]).moveToX(rootItemMessage.getImageLocation()[0])
                    .moveFromY(mImage.getLocationOnScreen()[1] - 80).moveToY(rootItemMessage.getImageLocation()[1] - 120)
                    .scaleX((float) image.getWidth() / (float) mImage.getWidth())
                    .scaleY((float) image.getHeight() / (float) mImage.getHeight());
            AnimatorProperty textAm = text.createAnimatorProperty()
                    .moveFromX(tvTitle.getLocationOnScreen()[0]).moveToX(rootItemMessage.getTextLocation()[0])
                    .moveFromY(tvTitle.getLocationOnScreen()[1] - 80).moveToY(rootItemMessage.getTextLocation()[1] - 120);
            animatorGroup.runParallel(imageAm, textAm);
            animatorGroup.setStateChangedListener(new Animator.StateChangedListener() {
                @Override
                public void onStart(Animator animator) {

                }

                @Override
                public void onStop(Animator animator) {

                }

                @Override
                public void onCancel(Animator animator) {

                }

                @Override
                public void onEnd(Animator animator) {
                    image.setVisibility(Component.INVISIBLE);
                    text.setVisibility(Component.INVISIBLE);
                }

                @Override
                public void onPause(Animator animator) {

                }

                @Override
                public void onResume(Animator animator) {

                }
            });
            animatorGroup.start();
            this.isFistStart = true;
        }
    }

    private void setComponentsVisibility(int componentType) {
        tvTitle.setVisibility(componentType);
        mImage.setVisibility(componentType);
        mListContainer.setVisibility(componentType);
    }

    private static class CityModel {
        int drawableRes;
        String title;

        public CityModel(int drawableRes, String title) {
            this.drawableRes = drawableRes;
            this.title = title;
        }
    }

    private class CityGridAdapter extends BaseItemProvider {
        private List<CityModel[]> list;
        private Context context;

        public CityGridAdapter(List<CityModel[]> list, Context context) {
            this.list = list;
            this.context = context;
        }

        @Override
        public int getCount() {
            return list == null ? 0 : list.size();
        }

        @Override
        public Object getItem(int position) {
            if (list != null && position >= 0) {
                return list.get(position);
            }
            return null;
        }

        @Override
        public long getItemId(int position) {
            return position;
        }

        @Override
        public Component getComponent(int i, Component component, ComponentContainer componentContainer) {
            final Component cpt;
            if (component == null) {
                cpt = LayoutScatter.getInstance(context).parse(ResourceTable.Layout_row_city_grid, null, false);
            } else {
                cpt = component;
            }
            ((Text) cpt.findComponentById(ResourceTable.Id_title1)).setText(list.get(i)[0].title);
            ((Image) cpt.findComponentById(ResourceTable.Id_image1)).setPixelMap(list.get(i)[0].drawableRes);
            cpt.findComponentById(ResourceTable.Id_dl_city1).setClickedListener(new Component.ClickedListener() {
                @Override
                public void onClick(ohos.agp.components.Component component) {
                    getRouter().pushController(
                            RouterTransaction.with(new CityDetailController(list.get(i)[0].drawableRes, list.get(i)[0].title))
                    );
                }
            });
            if (list.get(i)[1] != null) {
                ((Text) cpt.findComponentById(ResourceTable.Id_title2)).setText(list.get(i)[1].title);
                ((Image) cpt.findComponentById(ResourceTable.Id_image2)).setPixelMap(list.get(i)[1].drawableRes);
                cpt.findComponentById(ResourceTable.Id_dl_city2).setClickedListener(new Component.ClickedListener() {
                    @Override
                    public void onClick(ohos.agp.components.Component component) {
                        getRouter().pushController(
                                RouterTransaction.with(new CityDetailController(list.get(i)[1].drawableRes, list.get(i)[1].title))
                        );
                    }
                });

            }

            return cpt;
        }
    }

    @Override
    public Component onCreateView(LayoutScatter inflater, ComponentContainer container, IntentParams savedViewState) {
        if (parse == null) {
            parse = inflater.parse(layoutRes, container, false);
        }
        return parse;
    }

}
